package com.hkyl.hospital.web.controller;

import com.github.pagehelper.PageInfo;
import com.hkyl.hospital.domain.ResultVo;
import com.hkyl.hospital.entity.Dept;
import com.hkyl.hospital.entity.DoctorSort;
import com.hkyl.hospital.service.DeptService;
import com.hkyl.hospital.service.DoctorSortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("doctorSort")
public class DoctorSortController {
    @Autowired
    private DoctorSortService doctorSortService;

    @Autowired
    private DeptService deptService;

    @PostMapping("save")
    public ResultVo save(@RequestBody DoctorSort doctorSort) {
        int rows = doctorSortService.save(doctorSort);
        return rows > 0 ? ResultVo.success("添加成功") : rows == -1 ? ResultVo.failure("该医师已在当天出诊") : ResultVo.failure("添加失败");

    }

    //响应到前台的查询所有
    @PostMapping("findAll")
    public ResultVo findAll() {
        List<Dept> depts = new ArrayList<>(doctorSortService.findAll().keySet());
        doctorSortService.setDept(depts);
        List<Dept> doctorByMedical = deptService.findAllWithDoctorByMedical();
        Map map = new HashMap<>();
        map.put("depts", depts);
        map.put("doctorByMedical", doctorByMedical);
        return ResultVo.success(map);
    }

    @PostMapping("find")
    public ResultVo findAll(@RequestBody Map map){
        List<Dept> depts = deptService.findAllByMedical();
        PageInfo<DoctorSort> pageInfo = doctorSortService.selectAll(map);
        Map data = new HashMap<>();
        data.put("depts", depts);
        data.put("pageInfo", pageInfo);
        return ResultVo.success(data);
    }

    @PostMapping("update")
    public ResultVo update(@RequestBody DoctorSort doctorSort) {
        int rows = doctorSortService.update(doctorSort);
        return rows > 0 ? ResultVo.success("修改成功") : rows == -1 ? ResultVo.success("当前医师已在所选择天出诊") : ResultVo.failure("修改失败");
    }

    @PostMapping("delete")
    public ResultVo delete(@RequestBody String sortId) {
        if (StringUtils.hasText(sortId)) {
            throw new RuntimeException("id为空");
        }
        int rows = doctorSortService.delete(Integer.valueOf(sortId));
        return rows > 0 ? ResultVo.success("删除成功") : ResultVo.failure("删除失败");
    }
}
